//
//  TodaysAddViewController.m
//  TodaysPlan
//
//  Created by 寺田 篤史 on 11/10/09.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "TodaysAddViewController.h"
#import "TodaysPlanMemoViewController.h"
#import "TodaysPlanDataModel.h"
#import "SqliteDB.h"
#import "ConfigManager.h"

#define TASK_TAG @"task"
#define PRIORITY_TAG @"priority"

@implementation TodaysAddViewController
@synthesize keys;
@synthesize dataSource;
@synthesize selectDate;
@synthesize instanceArray;

- (id)initWithTodaysPlan:(TodaysPlan *)aTodaysplan{
    if ((self = [super init])){
        todaysplan = [aTodaysplan retain];
        ConfigManager *cfg = [[[ConfigManager alloc] init] autorelease];
        [cfg.cfgPkey setValueInt:todaysplan.pkey];
        [cfg.cfgTaskData setValueString:todaysplan.task];
        [cfg.cfgMemoData setValueString:todaysplan.memo];
        [cfg.cfgPriority setValueString:todaysplan.priority];
        [cfg.cfgReminderDate setValueString:todaysplan.reminderDate];
        [cfg.cfgReminder setValueBool:todaysplan.reminder];
        [cfg.cfgDone setValueString:todaysplan.done];
        //ナビゲーションバーにボタンを追加
        UIBarButtonItem *closeButton = [[[UIBarButtonItem alloc]
                                        initWithTitle:NSLocalizedString(@"backButton", "back button name")
                                        style:UIBarButtonItemStylePlain
                                        target:self
                                        action:@selector(back:)
                                        ] autorelease];
        self.navigationItem.leftBarButtonItem = closeButton;
        
        UIBarButtonItem *trashButton =[[[UIBarButtonItem alloc]
                                        initWithBarButtonSystemItem:UIBarButtonSystemItemTrash
                                        target:self action:@selector(trash:)] autorelease];
        self.navigationItem.rightBarButtonItem = trashButton;
    }
    return self;
}
- (id)init{
    if ((self = [super init])){
        ConfigManager *cfg = [[[ConfigManager alloc] init] autorelease];
        [cfg.cfgPkey setValueInt:0];
        [cfg.cfgTaskData setValueString:nil];
        [cfg.cfgMemoData setValueString:@""];
        [cfg.cfgPriority setValueString:@"0"];
        [cfg.cfgReminderDate setValueBool:0];
        [cfg.cfgReminder setValueString:nil];
        [cfg.cfgDone setValueString:@"0"];

        //ナビゲーションバーにボタンを追加
        UIBarButtonItem *closeButton = [[[UIBarButtonItem alloc]
                                        initWithTitle:NSLocalizedString(@"closeButton", "close button name")
                                        style:UIBarButtonItemStylePlain
                                        target:self
                                        action:@selector(closeAddTodaysPlan:)
                                        ] autorelease];
        self.navigationItem.leftBarButtonItem = closeButton;
        
    }
    return self;
}
- (void)loadView{
    [super loadView];
    CGRect headerTitleSubtitleFrame = CGRectMake(0, 0, 200, 44);    
    UIView* _headerTitleSubtitleView = [[[UILabel alloc] initWithFrame:headerTitleSubtitleFrame] autorelease];
    _headerTitleSubtitleView.backgroundColor = [UIColor clearColor];
    _headerTitleSubtitleView.autoresizesSubviews = YES;
    
    CGRect titleFrame = CGRectMake(0, 2, 200, 24);  
    UILabel *titleView = [[[UILabel alloc] initWithFrame:titleFrame] autorelease];
    titleView.backgroundColor = [UIColor clearColor];
    titleView.font = [UIFont boldSystemFontOfSize:20];
    titleView.textAlignment = UITextAlignmentCenter;
    titleView.textColor = [UIColor whiteColor];
    titleView.shadowColor = [UIColor darkGrayColor];
    titleView.shadowOffset = CGSizeMake(0, -1);
    titleView.text = NSLocalizedString(@"addTitle", "addTitle is TodaysAddView page");
    titleView.adjustsFontSizeToFitWidth = YES;
    [_headerTitleSubtitleView addSubview:titleView];
    
    CGRect subtitleFrame = CGRectMake(0, 24, 200, 44-24);   
    UILabel *subtitleView = [[[UILabel alloc] initWithFrame:subtitleFrame] autorelease];
    subtitleView.backgroundColor = [UIColor clearColor];
    subtitleView.font = [UIFont boldSystemFontOfSize:13];
    subtitleView.textAlignment = UITextAlignmentCenter;
    subtitleView.textColor = [UIColor whiteColor];
    subtitleView.shadowColor = [UIColor darkGrayColor];
    subtitleView.shadowOffset = CGSizeMake(0, -1);
    NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];;
    [df setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:NSLocalizedString(@"locale", "Date locale")] autorelease]];
    df.dateFormat  = NSLocalizedString(@"selectDate", "Date Format");
    NSString *date = [df stringFromDate:self.selectDate];
    subtitleView.text = date;
    subtitleView.adjustsFontSizeToFitWidth = YES;
    [_headerTitleSubtitleView addSubview:subtitleView];
    
    _headerTitleSubtitleView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
                                                 UIViewAutoresizingFlexibleRightMargin |
                                                 UIViewAutoresizingFlexibleTopMargin |
                                                 UIViewAutoresizingFlexibleBottomMargin);
    
    self.navigationItem.titleView = _headerTitleSubtitleView;
    self.tableView = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
    keys =[[NSArray alloc] initWithObjects:@"header",@"detail",nil];
    NSArray *object1 = [NSArray arrayWithObjects:@"task",nil];
    NSArray *object2 = [NSArray arrayWithObjects:@"memo",@"priority",@"reminder",@"reminderDate",nil];
    NSArray *objects = [NSArray arrayWithObjects:object1,object2,nil];
    dataSource = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    CGRect buttonFrame = CGRectMake(50, 300, 200, 44);
    button.frame = buttonFrame;
    [button addTarget:self action:@selector(registData:) forControlEvents:UIControlEventTouchDown];
    
    [self.view addSubview:button];
	instanceArray = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithBool:NO],nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (NSDate *)setLabelData:(NSDate *)date{
    return date;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [keys count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    id key = [keys objectAtIndex:section];
    return [[dataSource objectForKey:key] count];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
        [toggleControl toggleOn:[config.cfgDone getValueBool]];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.backgroundColor = [UIColor whiteColor];
    //task name
    if(indexPath.section == 0){
        toggleControl = [[ToggleImageControl alloc] initWithFrame:CGRectMake(25, 10, 25, 25)];
        [cell addSubview: toggleControl];
        
        cell.detailTextLabel.text = NSLocalizedString(@"taskdetail","task detail");
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UITextField *taskTextField = [[[UITextField alloc] initWithFrame:CGRectMake(50,10,250,25)] autorelease];
        //taskTextField.text = todaysplan.task;
        ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
        taskTextField.text = [config.cfgTaskData getValueString];
        taskTextField.textAlignment = UITextAlignmentLeft;
        taskTextField.keyboardType = UIKeyboardTypeDefault;
        taskTextField.returnKeyType = UIReturnKeyDone;
        taskTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        taskTextField.delegate = self;
        //[taskTextField becomeFirstResponder];
        taskTextField.tag = 0;
        [cell addSubview:taskTextField];
    }
    else if(indexPath.section == 1){
        //memo
        if(indexPath.row == 0){
            cell.textLabel.text = NSLocalizedString(@"memo","memo text");
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            UILabel *reminderDateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(155.0, 12.0, 100.0, 25.0)] autorelease];
            //reminderDateLabel.text = todaysplan.memo;
            ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            reminderDateLabel.text = [config.cfgMemoData getValueString];
            reminderDateLabel.textAlignment = UITextAlignmentLeft;
            reminderDateLabel.font = [UIFont systemFontOfSize: [UIFont systemFontSize]];
            reminderDateLabel.textColor = [UIColor darkGrayColor];
            [cell.contentView addSubview: reminderDateLabel];
        }
        //priority
        else if(indexPath.row == 1){
            cell.textLabel.text = NSLocalizedString(@"priority","priority text");
            UISegmentedControl *prioritySegmentedControl = [[[UISegmentedControl alloc] initWithFrame:CGRectMake(170, 5, 125, 35)] autorelease];
            //prioritySegmentedControl.tag = PRIORITY_TAG;
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priorityL","priority Low index text") atIndex:0 animated:NO];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priorityM","priority Middle index text") atIndex:1 animated:NO];
            [prioritySegmentedControl insertSegmentWithTitle:NSLocalizedString(@"priorityH","priority High text") atIndex:2 animated:NO];
            //prioritySegmentedControl.selectedSegmentIndex = [todaysplan.priority intValue];
            ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            prioritySegmentedControl.selectedSegmentIndex = [[config.cfgPriority getValueString] intValue];
            [prioritySegmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview: prioritySegmentedControl];
        }
        //reminder
        else if(indexPath.row == 2){
            cell.textLabel.text = NSLocalizedString(@"reminder","reminder text");
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            UISwitch *sw = [[[UISwitch alloc] init] autorelease];
            sw.center = CGPointMake(255, 22.5);
            BOOL isDisp = [config.cfgReminder getValueBool];
            sw.on = isDisp;
            [sw addTarget:self action:@selector(switchAction:)
            forControlEvents:UIControlEventValueChanged];
            [cell addSubview:sw];
        }
        //reminderDate
        else if(indexPath.row == 3){
            cell.textLabel.text = NSLocalizedString(@"reminderDate","reminderDate text");
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            //if(todaysplan.reminderDate !=nil){
            if([config.cfgReminderDate getValueString] != nil){
                UILabel *reminderDateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(155.0, 12.0, 100.0, 25.0)] autorelease];
                NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
                [inDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
                //NSString *inputDateStr = todaysplan.reminderDate;
                NSString *inputDateStr = [config.cfgReminderDate getValueString];
                NSDate *inputDate = [inDateFormatter dateFromString:inputDateStr];	
                NSString *reminderDate = [NSDateFormatter localizedStringFromDate:inputDate
                                                                        dateStyle:NSDateFormatterNoStyle
                                                                        timeStyle:NSDateFormatterShortStyle];    
                
                reminderDateLabel.text = reminderDate;
                reminderDateLabel.textAlignment = UITextAlignmentRight;
                reminderDateLabel.font = [UIFont systemFontOfSize: [UIFont systemFontSize]];
                reminderDateLabel.textColor = [UIColor darkGrayColor];
                [inDateFormatter release];
                [cell.contentView addSubview: reminderDateLabel];
            }
            
            
            
            //ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
            //NSString *reminderDate = [config.cfgReminderDate getValueString];
            /*
            
            if(todaysplan.reminderDate != nil & reminderDate == nil){
                UILabel *reminderDateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(155.0, 12.0, 100.0, 25.0)] autorelease];
                NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
                //[inDateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"US"] autorelease]];
                [inDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
                NSString *intputDateStr = todaysplan.reminderDate;
                NSDate *inputDate = [inDateFormatter dateFromString:intputDateStr];	
                //NSDateFormatter *outDateFormatter = [[NSDateFormatter alloc] init];
                //[outDateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"US"] autorelease]];
                //NSString *outputDateFormatterStr = @"HH:mm";
                //[outDateFormatter setDateFormat:outputDateFormatterStr];
                NSString *reminderDate = [NSDateFormatter localizedStringFromDate:inputDate
                                                                        dateStyle:NSDateFormatterNoStyle
                                                                        timeStyle:NSDateFormatterShortStyle];    

                reminderDateLabel.text = reminderDate;
                reminderDateLabel.textAlignment = UITextAlignmentRight;
                reminderDateLabel.font = [UIFont systemFontOfSize: [UIFont systemFontSize]];
                reminderDateLabel.textColor = [UIColor darkGrayColor];
                [config.cfgReminderDate setValueString:intputDateStr];
                [inDateFormatter release];
                //[outDateFormatter release];
                [cell.contentView addSubview: reminderDateLabel];
            }
            else if (todaysplan.reminderDate != nil & reminderDate != nil){
                UILabel *reminderDateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(155.0, 12.0, 100.0, 25.0)] autorelease];
                reminderDateLabel.text = reminderDate;
                reminderDateLabel.textAlignment = UITextAlignmentRight;
                reminderDateLabel.font = [UIFont systemFontOfSize: [UIFont systemFontSize]];
                reminderDateLabel.textColor = [UIColor darkGrayColor];
                [config.cfgReminderDate setValueString:reminderDate];
                
                //[inDateFormatter release];
                //[outDateFormatter release];
                [cell.contentView addSubview: reminderDateLabel];
                
            }
             */
            else{
                cell.detailTextLabel.text = NSLocalizedString(@"reminderdetail", "reminder detail");
            }
        }
    }
    return cell;
}    
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	NSString *ret = nil;
	
	switch (section) {
		case 0:
			//ret = @"検索結果の基本表示設定";
			break;
		default:
			break;
	}
	
	return ret;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        //task
        case 0:
        {
            // セルの選択色解除(UITableViewCellSelectionStyleNone設定時は不要)
            [tableView deselectRowAtIndexPath:indexPath animated:NO];
            
                // 現状の選択状態を判定
                if([[instanceArray objectAtIndex:indexPath.row] boolValue]) {
                    // 非選択に値を書き換え
                    [instanceArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:NO]];
                } else {
                    // 選択に値を書き換え
                    [instanceArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
                }
                [toggleControl toggleOn:[[instanceArray objectAtIndex:indexPath.row] boolValue]];
            
        }
            break;
        //memo priority reminder
        case 1:
        {
            //memo
            if(indexPath.row == 0){
                TodaysPlanMemoViewController *vc = [[[TodaysPlanMemoViewController alloc] init] autorelease];
                [self.navigationController pushViewController:vc animated:YES];
            }
            //reminder
            else if(indexPath.row == 3){
                DatePickerViewController *vc = [[[DatePickerViewController alloc] init] autorelease];;
                [vc setDelegate:self];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
        default:
            break;
    }
}
- (void)registData:(id)sendar
{
    DLog(@"regist button event start");
    ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
    int pkey = [config.cfgPkey getValueInt];
    NSString *task = [config.cfgTaskData getValueString];
    NSString *memo = [config.cfgMemoData getValueString];
    NSString *priority = [config.cfgPriority getValueString];
    NSString *reminderDate = [config.cfgReminderDate getValueString];
    int reminder = [config.cfgReminder getValueBool] ? 1 : 0;
    NSString *done = [config.cfgDone getValueString];
    SqliteDB *db = [[[SqliteDB alloc] init] autorelease];
    [db initializeDatabaseIfNeeded];
    
    if(todaysplan.pkey){
        [TodaysPlanDataModel updateTodaysPlan:pkey task:task 
                                         memo:memo priority:priority 
                                     reminder:reminder reminderDate:reminderDate done:done];
        [[self navigationController]popViewControllerAnimated:YES]; //todo
    }else{
        
        NSDateFormatter *createDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [createDateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString* registDateStr = [createDateFormatter stringFromDate:self.selectDate];
        [TodaysPlanDataModel insertTodaysPlan:registDateStr task:task memo:memo priority:priority reminder:reminder reminderDate:reminderDate];
        [self dismissModalViewControllerAnimated:YES]; //todo
    }
    DLog(@"regist button event  end");    
}

- (void)closeAddTodaysPlan:(id)sender{
    [self dismissModalViewControllerAnimated:YES];
}
- (void)back:(id)sender{
    [[self navigationController]popViewControllerAnimated:YES];
}
- (void)trash:(id)sender{
    DLog(@"trash button event start");
    ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
    int pkey = [config.cfgPkey getValueInt];
    SqliteDB *db = [[[SqliteDB alloc] init] autorelease];
    [db initializeDatabaseIfNeeded];
    if(todaysplan.pkey){
        [TodaysPlanDataModel deleteTodaysPlan:pkey];
    }
    [[self navigationController]popViewControllerAnimated:YES]; 
    DLog(@"trash button event  end");
}
#pragma mark -
#pragma mark Table view delegate
- (void)textFieldShouldReturn:(UITextField *)tf {
	if( [tf canResignFirstResponder] ) [tf resignFirstResponder];
}
- (void)segmentAction:(UISegmentedControl*)sender
{
    ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
    [config.cfgPriority setValueString:[NSString stringWithFormat:@"%d", sender.selectedSegmentIndex]];
}
- (void)switchAction:(UISwitch*)sender
{
    ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
    [config.cfgReminder setValueBool:sender.on];    
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 0 ) {
        ConfigManager *config = [[[ConfigManager alloc] init] autorelease];
        [config.cfgTaskData setValueString:textField.text];
    }
}
#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
- (void)dealloc{
    [keys release];
    [dataSource release];
    [selectDate release];
    [toggleControl release];
    [super dealloc];
}
@end
